package com.android.samples.mediastore.hms.drive.operate

import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.text.TextUtils
import android.util.Log
import com.huawei.cloud.services.drive.Drive
import com.huawei.cloud.services.drive.model.About
import dagger.hilt.android.scopes.ViewModelScoped

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import javax.inject.Inject

/**
 * 可以通过About.Get接口获取到用户华为云空间信息，例如空间容量大小，允许上传的最大文件大小等。
 */


@ViewModelScoped
class UserInfoHelper @Inject constructor(private val drive: Drive) {
    private val TAG = "UserInfoHelper"

    suspend fun getAbout(): About? {
        return withContext(Dispatchers.IO) {
            var response: About? = null
            try {
                val about = drive.about()
                response = about.get().setFields("*").execute()
            } catch (e: Exception) {
                Log.e(TAG, "getInfo error: $e")
            }
            response
        }
    }


    /**
     * 判断是否要提示用户更新协议
     *
     * @param about 返回的About响应
     */
    fun checkUpdateProtocol(context: Context, about: About) {
        Log.d(TAG, "checkUpdate: $about")
        val updateValue = about["needUpdate"]
        var isNeedUpdate = false
        if (updateValue is Boolean) {
            isNeedUpdate = updateValue
        }
        Log.d(TAG, "checkUpdateProtocol: isNeedUpdate = $isNeedUpdate")
        if (!isNeedUpdate) {
            return
        }
        //如果需要更新，通过url启动授权页面
        val urlValue = about["updateUrl"]
        var url: String? = ""
        if (urlValue is String) {
            url = urlValue
        }
        if (TextUtils.isEmpty(url)) {
            return
        }
        val uri: Uri = Uri.parse(url)
        if ("https" != uri.scheme) {
            return
        }
        val intent = Intent(Intent.ACTION_VIEW, uri)
        try {
            context.startActivity(intent)
        } catch (e: ActivityNotFoundException) {
            Log.e(TAG, "Activity Not found")
        }
    }
}